<?php

namespace app\api\controller;

use app\api\basic\BaseController;
use app\api\logic\WechatUserLogic;
use support\Request;
use app\api\logic\CollectionLogic;
use app\cassification\logic\ClassificationDictionaryLogic;
use app\Cnarea\logic\CnareaLogic;
use app\feedback\logic\feedbackLogic;
use app\finance\logic\financeLogic;
use app\policy\logic\PolicyLogic;
use app\space\logic\spaceLogic;
use app\supplyDemand\logic\supplyDemandLogic;
use app\recruitment\logic\recruitmentLogic;
use app\reservation\logic\reservationLogic;
use app\signup\logic\signupLogic;
use plugin\saiadmin\app\logic\system\SystemUploadfileLogic;
use app\api\annotation\LoginRequired;
class UserInfoController extends BaseController {
   protected $userInfo;

    /**
     * 当前登陆管理员ID
     */
    protected $userId;

    /**
     * 当前登陆管理员账号
     */
    protected $userName;
    public function __construct()
    {   
        parent::__construct();
        $this->userId=request()->userId;
        $this->userName=request()->userName;
        $this->userInfo=request()->userInfo;
    }
  
  public function getUsInfo(){

    $WechatUserLogic=new WechatUserLogic();
    $collectionLogic=new CollectionLogic();
    $userInfo=$WechatUserLogic->field('openid,nickname,avatar,gender,real_name,lang_code,phone,is_auth')->find($this->userId);
    if(!$userInfo) return $this->fail('用户信息不存在');
   
    $userinfoData=$userInfo->toArray();
    $user_collection=$collectionLogic->getMe($this->userId);
    $userinfoData['policy_num']=$user_collection[1]??0;
    $userinfoData['supply_demand_num']=$user_collection[2]??0;
    $userinfoData['talents_num']=$user_collection[3]??0;
    $userinfoData['space_num']=$user_collection[4]??0;
    return $this->success($userinfoData);
   
  }
  /**
   * 更新用户信息
   */
  public function updateUserInfo(Request $request){
    $param = $request->more([
        ['nickname', ''],
        ['avatar', ''],
        ['gender', 3],
        ['city', ''],
        ['province', ''],
        ['country', ''],
        ['real_name',''],
        ['phone',''],
        ['is_auth',''],
        ['lang_code','']
    ]);
    $param = array_filter($param, function($value) {
        return $value !== '';
    });
    if(!$param) return $this->fail('缺少数据');
    $WechatUserLogic=new WechatUserLogic();
    $res=$WechatUserLogic->where('user_id',$this->userId)->update($param);
    if($res) return $this->success('更新成功');
    return $this->fail('更新失败');
  }
  //惠企政策
  public function myPolicy(Request $request){
      $param = $request->more([
            ['limit',10],
            ['page',1]
        ]);
      $ebPolicy=new PolicyLogic();
      $policyData=$ebPolicy->getPolicy($this->userId,$param['limit']);
      return $this->success(['data'=>$policyData->items(),'total'=>$policyData->total()]);
  }
  //我的供需
  public function mySupplyDemand(Request $request){
     $param = $request->more([
            ['limit',10],
            ['page',1]
        ]);
       $ebSupplyDemand=new supplyDemandLogic();
       $supplyDemandData=$ebSupplyDemand->getSupplyDemand($this->userId,$param['limit']);
        return $this->success(['data'=>$supplyDemandData->items(),'total'=>$supplyDemandData->total()]);        
  
  }
  //人才需求
   public function myRecruitment(Request $request){
    $param=[
      'limit'=>$request->limit??10,
      'page'=>$request->page??1
    ];
    $ebRecruitmentLogic=new RecruitmentLogic();
    $ebRecruitmentLogicData=$ebRecruitmentLogic->getRecruitment($this->userId,$param['limit']);
    return $this->success(['data'=>$ebRecruitmentLogicData->items(),'total'=>$ebRecruitmentLogicData->total()]);
  
  }
  //意向空间
  public function mySpace(Request $request){
    $param = $request->more([
            ['limit',10],
            ['page',1]
        ]);
     $ebSpaceLogic=new spaceLogic();
     $ebSpaceLogicData=$ebSpaceLogic->getSpace($this->userId,$param['limit']);
      return $this->success(['data'=>$ebSpaceLogicData->items(),'total'=>$ebSpaceLogicData->total()]);        
  }
  //我的金融
  public function myFinance(Request $request){
    $param = $request->more([
        ['limit',10],
        ['page',1],
        ['finance_category','']
    ]);
   
    $ebFinanceLogic=new financeLogic();
    $ebFinanceLogicData=$ebFinanceLogic->getFinance($this->userId,$param['finance_category'],$param['limit']);
    return $this->success($ebFinanceLogicData);
  }
  //我的活动

  public function myActivity(Request $request){
    $param = $request->more([
        ['limit',10],
        ['page',1],
    ]);
    $ebSignupLogic=new signupLogic();
    $ebSignupLogicData=$ebSignupLogic->getSignupList($this->userId,$param['limit']);
    $data=$ebSignupLogicData->items();
    foreach($data as $item){
        if(isset($item['activity_start_time']) && isset($item['activity_end_time'])){
            $item['activity_status_text']=  '';
            if($item['activity_end_time'] <= date('Y-m-d H:i:s',time())){
               $item['activity_status_text']= '已完成';
            }elseif($item['activity_start_time'] <=date('Y-m-d H:i:s',time())){
                 $item['activity_status_text']=  '进行中';
            }else{
                 $item['activity_status_text']=  '未开始';
            }
          }
         
    }
    unset($item); 
    return $this->success(['data'=>$data,'total'=>$ebSignupLogicData->total()]);
  }
   //我的预约
  public function myReservation(Request $request){
     $param = $request->more([
        ['limit',10],
        ['page',1],
    ]);
     $reservation=new reservationLogic();
     $reservationList=$reservation->getReservationList($this->userId,$param['limit']);
      return $this->success(['data'=>$reservationList->items(),'total'=>$reservationList->total()]);
  }
  //我的反馈
    #[LoginRequired(required:false)]
  public function myFeedback(Request $request){
      
     $param = $request->more([
        ['page',1],
        ['limit',10],
        ['status','']
    ]);
     $feedback=new feedbackLogic();
     $list=$feedback->search(['user_id'=>$this->userId,'status'=>$param['status']])
     ->field('feedback_id,feedback_classify,user_name,
     contact_number,feedback_content,create_time,status,reply_content,reply_time')
     ->order('create_time desc')
     ->paginate($param['limit']);
     return $this->success(['data'=>$list->items(),'total'=>$list->total()]);
  }
  public function myFeedbackDetali(Request $request){

     $param = $request->more([
        ['feedback_id',''],
    ]);
    if(!$param['feedback_id']) return $this->fail('缺少反馈id');
     $feedback=new feedbackLogic();
     $list=$feedback->search(['user_id'=>$this->userId,'feedback_id'=>$param['feedback_id']])
     ->field('feedback_id,feedback_classify,user_name,
     contact_number,feedback_content,create_time,status,reply_content,reply_time,files')
     ->order('create_time desc')
     ->find();
     if($list) return $this->success($list->toArray());
      return $this->fail('反馈信息不存在');
    
  }
  //留言箱
  public function mySaveFeedback(Request $request){
    $param = $request->more([
        ['feedback_classify',''],
        ['user_name',''],
        ['contact_number',''],
        ['feedback_content',''],
        ['files',[]]
    ]);
      
    $validate = $this->validate->rule([
        'feedback_classify'=>'require',
        'user_name'    => 'require|max:50',
        'contact_number'   => 'require|regex:/^1[3-9]\d{9}$/',
        'feedback_content'   => 'require'
    ])->message([
        'feedback_classify.require' => '请选择留言分类',
        'user_name.require' => '请输入联系人',
        'contact_number.require' => '请输入联系电话',
        'contact_number.regex'  => '联系电话格式不正确',
        'feedback_content.require' => '反馈内容',
        
    ]);
     if (!$validate->check($param)) {
        return $this->fail($validate->getError());
    }
    $param['user_id']=$this->userId;
   
    $feedback=new feedbackLogic();
    $feedback_classify=new ClassificationDictionaryLogic();
    $feedbackList=$feedback->search([
      'user_id'=>$this->userId,
      'feedback_content'=>$param['feedback_content'],
      'contact_number'=>$param['contact_number'],
      'user_name'=>$param['user_name']
    ])->findOrEmpty();
    if(!$feedbackList->isEmpty()) return $this->fail('您已提交过相同的反馈');
    $check_feedback_classify=$feedback_classify->search(['classification_type'=>9,'dictionary_id'=>$param['feedback_classify']])
    ->findOrEmpty();
    if($check_feedback_classify->isEmpty()) return $this->fail('反馈分类不存在');
    $res=$feedback->create($param);
    if($res)return $this->success('反馈成功');
    return $this->fail('反馈失败');
  }
  //上传附件
  #[LoginRequired(required: false)]
  public function uploadImage(Request $request)
    {
        $logic = new SystemUploadfileLogic();
      
        $type = $request->input('mode', 'system');
        if ($type == 'local') {
            return $this->success($logic->uploadBase('image', true));
        }
        return $this->success($logic->uploadBase('image'));
    }
    #[LoginRequired(required:false)]
    public function getAddressSelect(Request $request)
    {
       $CnareaLogic=new CnareaLogic();
        $where = $request->more([
            ['level', ''],
            ['parent_code','']
        ]);
       
        if(empty($where['level'])) return $this->fail('缺少层级');
        $query = $CnareaLogic->search(['parent_code'=>$where['parent_code']])->where('level','<=',$where['level'])->field('name as label,area_code as value,level,parent_code');
        $data = $CnareaLogic->getAll($query);
        // switch ($where['level']) {
        //     case 1:
        //          $name='全国';            
        //         break;
        //    case 2:
        //         $name='全省';
        //         break;
        //     case 3:
        //         $name='全市';
        //         break;     
        // }
        // if($data){
        //     array_unshift($data, ['label' => $name, 'value' => 0]);
        // }else{
        //     $data = [['label' => $name, 'value' => 0]];
        // }
       
        return $this->success($data);
    }


 
}